package com.saifan.wyy_ov.ui.communitylife;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.data.bean.PermissionsBean;
import com.saifan.wyy_ov.data.bean.PopBean;
import com.saifan.wyy_ov.data.bean.RentalBean;
import com.saifan.wyy_ov.data.bean.RentalRequestBean;
import com.saifan.wyy_ov.data.bean.RoomInfoBean;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.IListViewOnClick;
import com.saifan.wyy_ov.model.interfaces.ResponseData;
import com.saifan.wyy_ov.ui.view.BaseActivity;
import com.saifan.wyy_ov.ui.view.LabelView;
import com.saifan.wyy_ov.ui.view.RefreshLayout;
import com.saifan.wyy_ov.utils.CommonAdapter;
import com.saifan.wyy_ov.utils.PopUtil;
import com.saifan.wyy_ov.utils.PriceUtils;
import com.saifan.wyy_ov.utils.StringUtil;
import com.saifan.wyy_ov.utils.ToastUtil;
import com.saifan.wyy_ov.utils.ViewHolderHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * @version V1.0.0
 * @author: lomasky
 * @date: 2015-5-19 17:36:23
 * @descrption 租售信息
 */

public class RentalinfoActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener {
    private Toolbar toolbar;
    private CheckBox checkBox1;
    private CheckBox checkBox2;
    private CheckBox checkBox3;
    private View loadlay;
    private ListView listView;
    private ArrayList<PopBean> rentalTypes, propertyTypes, houseTypes;
    private int rentalTypesIndex = -1, propertyTypesIndex = -1, houseTypesIndex = -1;

    private PopupWindow popupWindow;
    private RefreshLayout refreshLayout;
    private RoomInfoBean roomInfoBean;
    private int page = 0;
    List<RentalBean> beans = new ArrayList<>();
    private CommonAdapter<RentalBean> adapter;
    private GetData getData;
    private RentalRequestBean requestBean;

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            if (msg.what == 1) {
                rentalTypesIndex = msg.arg1;
                page = 0;
                requestBean.setCZCS_LX(rentalTypes.get(rentalTypesIndex).getKey());
                query();

            } else if (msg.what == 2) {
                propertyTypesIndex = msg.arg1;
                page = 0;
                requestBean.setCZCS_WYLXMC(propertyTypes.get(propertyTypesIndex).getValue());
                query();


            } else if (msg.what == 3) {
                houseTypesIndex = msg.arg1;
                page = 0;

                requestBean.setCZCS_HXMC(houseTypes.get(houseTypesIndex).getValue());
                query();

            }

        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        roomInfoBean = getRoomInfoBean();
        requestBean = new RentalRequestBean();
        getData = new GetData();
        rentalTypes = new ArrayList<>();
        rentalTypes.add(new PopBean("出租", 1));
        rentalTypes.add(new PopBean("出售", 2));
        rentalTypes.add(new PopBean("不限", 0));
        propertyTypes = new ArrayList<>();
        propertyTypes.add(new PopBean("住宅", "住宅"));
        propertyTypes.add(new PopBean("商铺", "商铺"));
        propertyTypes.add(new PopBean("写字楼", "写字楼"));
        propertyTypes.add(new PopBean("其它", "其它"));
        propertyTypes.add(new PopBean("不限", ""));

        houseTypes = new ArrayList<>();
        houseTypes.add(new PopBean("1室", "1室"));
        houseTypes.add(new PopBean("2室", "2室"));
        houseTypes.add(new PopBean("3室", "3室"));
        houseTypes.add(new PopBean("不限", ""));
        setContentView();
        initAdapter();
        query();
    }

    public void setContentView() {
        setContentView(R.layout.activity_rentalinfo);
        loadlay = findViewById(R.id.loading_lay);
        this.refreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);
        this.checkBox3 = (CheckBox) findViewById(R.id.checkBox3);
        this.checkBox2 = (CheckBox) findViewById(R.id.checkBox2);
        this.checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
        this.listView = (ListView) findViewById(R.id.listView);
        this.toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        checkBox3.setOnCheckedChangeListener(this);
        checkBox2.setOnCheckedChangeListener(this);
        checkBox1.setOnCheckedChangeListener(this);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 0;
                refreshLayout.setRefreshing(true);
                query();
            }
        });

        refreshLayout.setOnLoadListener(new RefreshLayout.OnLoadListener() {
            @Override
            public void onLoad() {
                refreshLayout.setLoading(true);
                page++;
                query();
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(RentalinfoActivity.this, RentalinfoItemActivity.class);
                intent.putExtra("data", beans.get(position));
                startActivity(intent);


            }
        });
    }

    public void query() {
        requestBean.setXMBS(roomInfoBean.getXMBS());
        requestBean.setPage(page);
        if (beans.isEmpty()) {
            loadlay.setVisibility(View.VISIBLE);
        }
        getData.getDataJson(this, Api.RentalInfo.RENTAL_INFO_LIST, requestBean, "", new ResponseData() {
            @Override
            public void onSuccess(String json) {
                List<RentalBean> list = new Gson().fromJson(json, new TypeToken<List<RentalBean>>() {
                }.getType());
                if (!list.isEmpty()) {
                    if (page == 0) {
                        beans = list;
                    } else {
                        beans.addAll(list);
                    }


                } else {
                    if (page > 0) {
                        ToastUtil.showToast(getBaseContext(), "信息已全部显示完毕！");
                        page--;
                    } else {
                        beans.clear();
                        ToastUtil.showToast(getBaseContext(), "暂无更多信息");
                    }

                }
                adapter.mDatas = beans;
                adapter.notifyDataSetChanged();
                loadlay.setVisibility(View.GONE);
                refreshLayout.setRefreshing(false);
                refreshLayout.setLoading(false);


            }

            @Override
            public void onFailed(String str) {
                loadlay.setVisibility(View.GONE);
                refreshLayout.setRefreshing(false);
                refreshLayout.setLoading(false);
                if (page > 0) page--;

            }
        });
    }

    public void initAdapter() {
        adapter = new CommonAdapter<RentalBean>(this, beans, R.layout.rentalinfo_item) {
            @Override
            public void convert(ViewHolderHelper helper, RentalBean item) {

                helper.setImageByUrl(R.id.CZCS_SLT, item.getCZCS_SLT());
                helper.setText(R.id.CZCS_JE, getString(R.string.rmb , PriceUtils.getPrice(item.getCZCS_JE())));
                helper.setText(R.id.CZCS_BT, StringUtil.returnShow(item.getCZCS_BT()));
                helper.setText(R.id.CZCS_HXMC, StringUtil.returnShow(item.getCZCS_HXMC()));
                helper.setText(R.id.CZCS_CZLX, StringUtil.returnShow(item.getCZCS_CZLX()));
                if (!StringUtil.isNullOrEmpty(item.getCZCS_FBSJ()) && item.getCZCS_FBSJ().length() > 10) {
                    helper.setText(R.id.CZCS_FBSJ, StringUtil.returnShow(item.getCZCS_FBSJ().substring(0, 10)));
                }


                LabelView label = helper.getView(12345);
                if (label == null) {
                    label = new LabelView(RentalinfoActivity.this);

                    label.setId(12345);

                }
                if (item.getCZCS_LX() == 1) {
                    label.setBackgroundColor(getResources().getColor(R.color.state3));
                    label.setTargetViewInBaseAdapter(helper.getView(R.id.CZCS_SLT), 92, 10, LabelView.Gravity.LEFT_TOP);
                    label.setText("出租");
                } else if (item.getCZCS_LX() == 2) {
                    label.setBackgroundColor(getResources().getColor(R.color.state1));
                    label.setTargetViewInBaseAdapter(helper.getView(R.id.CZCS_SLT), 92, 10, LabelView.Gravity.LEFT_TOP);
                    label.setText("出售");
                }


            }
        };

        listView.setAdapter(adapter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_rentalandsalesinformation, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            if (getRoomInfoBean().getUserType() == 2){
                for (PermissionsBean permissionsBean : getPermissions()){
                    if (permissionsBean.getYKQX_GNMC().equals("租售信息")){
                        startActivity(RentalinfoReleaseActivity.class);
                        return true;
                    }
                }
                ToastUtil.showToast(RentalinfoActivity.this, "您的权限不能进行此操作");
                return true;
            } else if (getRoomInfoBean().getUserType() == 3){
                ToastUtil.showToast(RentalinfoActivity.this, "您的权限不能进行此操作");
                return true;
            }


            startActivity(RentalinfoReleaseActivity.class);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {


        final int id = buttonView.getId();


        if (isChecked) {
            if (buttonView.getId() == R.id.checkBox1) {
                popupWindow = PopUtil.createPopupWindow(this, rentalTypes, new IListViewOnClick() {
                    @Override
                    public void onClick(int position) {
                        ((CheckBox) findViewById(id)).setText(rentalTypes.get(position).getName());
                        Message message = new Message();
                        message.arg1 = position;
                        message.what = 1;
                        handler.sendMessage(message);
                    }
                });
            } else if (buttonView.getId() == R.id.checkBox2) {
                popupWindow = PopUtil.createPopupWindow(this, propertyTypes, new IListViewOnClick() {
                    @Override
                    public void onClick(int position) {
                        ((CheckBox) findViewById(id)).setText(propertyTypes.get(position).getName());
                        Message message = new Message();
                        message.arg1 = position;
                        message.what = 2;
                        handler.sendMessage(message);
                    }
                });
            } else if (buttonView.getId() == R.id.checkBox3) {
                popupWindow = PopUtil.createPopupWindow(this, houseTypes, new IListViewOnClick() {
                    @Override
                    public void onClick(int position) {
                        ((CheckBox) findViewById(id)).setText(houseTypes.get(position).getName());
                        Message message = new Message();
                        message.arg1 = position;
                        message.what = 3;
                        handler.sendMessage(message);
                    }
                });


            }

            popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            popupWindow.showAsDropDown(buttonView);

        } else {
            popupWindow.dismiss();
        }
    }


}
